import 'package:flutter/material.dart';
import '../screens/system/fontsize_provider.dart';
import 'package:provider/provider.dart';

class MessageBox {
  // 显示更小的弹窗，适配移动端
  static void showMessageBox(BuildContext context, dynamic error, {bool isError = false}) {
    // 获取字体缩放比例
    late double fontScale = Provider.of<FontSizeProvider>(context).fontScale;
    String message;
    
    // 处理不同类型的错误信息
    if (error is String) {
      message = error;
    } else if (error is Exception) {
      String msg = error.toString();
      if (msg.startsWith('Exception: ')) {
        msg = msg.replaceAll('Exception: ', '');
      }
      message = msg;
    } else if (error is Error) {
      message = error.toString();
    } else {
      message = 'Unknown error';
    }
    
    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (BuildContext context) {
        // 获取屏幕宽度，用于计算弹窗最大宽度
        final screenWidth = MediaQuery.of(context).size.width;
        
        return AlertDialog(
          // 限制弹窗最大宽度为屏幕的70%，移动端更友好
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(8.0),
          ),
          // 减小内边距
          contentPadding: const EdgeInsets.fromLTRB(15, 10, 15, 5),
          titlePadding: const EdgeInsets.fromLTRB(15, 10, 15, 5),
          actionsPadding: const EdgeInsets.fromLTRB(15, 5, 10, 10),
          
          title: Text(
            isError ? 'Error' : 'Success',
            style: TextStyle(
              fontWeight: FontWeight.bold,
              // 减小标题字体
              fontSize: 16 * fontScale,
              color: isError 
                ? const Color.fromARGB(255, 255, 17, 0) 
                : const Color.fromARGB(255, 4, 170, 10)
            ),
          ),
          content: SingleChildScrollView(
            child: ConstrainedBox(
              // 进一步限制内容区域宽度
              constraints: BoxConstraints(
                maxWidth: screenWidth * 0.6,
              ),
              child: ListBody(
                children: <Widget>[
                  Text(
                    message,
                    // 减小内容字体
                    style: TextStyle(fontSize: 14 * fontScale),
                  ),
                ],
              ),
            ),
          ),
          actions: <Widget>[
            TextButton(
              child: Text(
                'OK',
                style: TextStyle(
                  fontSize: 14 * fontScale,
                  color: const Color(0xFF008363),
                ),
              ),
              onPressed: () {
                Navigator.of(context).pop();
              },
            ),
          ],
        );
      },
    );
  }
}
